package thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/*线程池
线程池是线程的管理机制，结局两个问题
1重复使用
控制线程数量
 */
public class ThreadPool {
    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(3);
        for (int i=0; i<5; i++){
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    Thread t1 = Thread.currentThread();
                    System.out.println(t1 + "正在执行任务");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("执行完毕");
                }

            };
            service.execute(r);
            System.out.println("将一个任务交给了线程池");
        }
        //service.shutdown();//关闭线程池
        service.shutdownNow();//立即关闭线程池，这种方式不友好
        System.out.println("线程池关闭了");
    }
}
